require("../util.js");
require("../component/components.js");
// require("../component/friendHeader.js");
require("../component/footer.js");
require("../../jsMt/util.js");
// require("../friend/init.js");
// var userInfo=JSON.parse(localStorage.getItem("userInfo"));
var userInfo=JSON.parse(sessionStorage.getItem("userInfo"));
if(!userInfo){
    location.href="/loginIndex"
}
console.log(userInfo)
var vm = new Vue({
    el:"#friendIndex",
    data:{
        loadFlag:false,
        token:"",
        uid:"",//用户id
        isShow:false,
        conversationType:"",
        circleId:"",//好友或者圈子id
        name:"",//好友或者圈子name
        img:"",//好友或者圈子头像
        type:"",//1 好友 2圈子 2消息
        text:"",//聊天内容
        indexs:1,
        num:"",
        userInfo:userInfo,//用户信息
        news:{},//消息
        newsList:[],//消息列表
        newsList1:[],//消息列表
        friendList:{},//好友列表
        circleList:{}, //圈子列表
        dynamicListType:1,
        pageNumber:1,
        friendDynamic:{},//好友动态列表
        friendDynamic1:[],
        friendDynamic2:[],
        messageRecordList:[],//历史聊天记录
        isScreen:"",
        postId:"",
        commentList:{},
        commentList1:[],
        commentList2:{},
        commentText:"",
        number:"",
        mediaId:"",
        getUser:{}
    },
    mounted:function(){
        this.searchObject = this.getQueryStringArgs();
        this.circleId=this.searchObject&&this.searchObject.circleId;
        this.uid=this.searchObject&&this.searchObject.uid;
        this.num=this.searchObject&&this.searchObject.num;
        if(this.searchObject&&this.searchObject.indexs){
            this.indexs=this.searchObject&&this.searchObject.indexs;
            this.getTab(this.indexs);
        }
        if(this.searchObject&&this.searchObject.type){
           this.type=this.searchObject&&this.searchObject.type;
           this.isShow=true;
            console.log(this.circleId)
        }
        this.getFriendList();
        //this.getCircleList();
        // this.getLogin();
        //localStorage.clear()
        //sessionStorage.clear()
    },
    methods:{
        bgimg:function(url){
            url = url?url:"";
            return {
                "background-image":'url("'+url+'"),url("")'
            }
        },
        /*获取查询字符对象*/
        getQueryStringArgs: function () {
            //取得查询字符串并去掉开头的问号
            var qs = (location.search.length > 0 ? location.search.substring(1) : ""),
                args = {},
                items = qs.length ? qs.split("&") : [],
                item = null,
                name = null,
                value = null,
                len = items.length;
            for (var i = 0; i < len; i++) {
                item = items[i].split("=");
                name = item[0];
                value = item[1];
                if (name.length) {
                    args[name] = value;
                }
            }
            return args;
        },
        //tab切换
        getTab:function(num){
            this.indexs=num;
            this.pageNumber=1;
            if(num==2){
                this.getFriendList();
            }else if(num==3){
                this.getCircleList();
            }else if(num==4){
                this.getFriendDynamic();
            }
        },
        //好友列表
        getFriendList:function(){
            var that=this;
            this.ajax({url:"/friend/getFriendList",data:{loginUid:userInfo.id||that.uid},dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.friendList=b.json.data;
                    if(that.type==1){
                        vm.getList(1);
                    }
                    //console.log(that.friendList)
                }else{
                    vm.$refs.prompt.toast("获取好友列表失败！")
                }
            });
        },
        //圈子列表
        getCircleList:function(){
            var that=this;
            this.ajax({url:"/friend/getCircleList",data:{loginUid:userInfo.id||that.uid},dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.circleList=b.json.data;
                    vm.getList(1);
                    //console.log(that.circleList)
                }else{
                    vm.$refs.prompt.toast("获取圈子列表失败！")
                }
            });
        },
        //好友查看筛选
        dynamicList:function(type){
            this.dynamicListType=type;
            this.getFriendDynamic();
        },
        //好友动态
        getFriendDynamic:function(){
            var that=this;
            var data={
                loginUid:userInfo.id||that.uid,
                type:that.dynamicListType,
                pageNumber:that.pageNumber
            };
            this.ajax({url:"/friend/getFriendDynamic",data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.friendDynamic=b.json.data;
                    that.friendDynamic1=that.friendDynamic.list;
                    if(that.friendDynamic.pageNumber>1){
                        if(that.friendDynamic.list.length>0) {
                            that.friendDynamic2 = that.friendDynamic2.concat(b.json.data.list);
                        }
                    }else{
                        that.friendDynamic2= that.friendDynamic1;
                    }
                    vm.loadFlag=false;
                    lazyload();
                }else{
                    that.friendDynamic={};
                    that.friendDynamic1=[];
                    that.friendDynamic2=[];
                    vm.$refs.prompt.toast("获取圈子列表失败！")
                }
            });
        },
        //跳转页面
        getNext:function(list,type){
            var path="/friend/circleBar?type="+type+"&circleId="+list.circleId+"&uid="+userInfo.id;
            // if(type==1){
            //     path+="&id="+list.uid+"&name="+encodeURI(list.name)+"&img="+list.headImg;
            // }else if(type==2){
            //     path+="&id="+list.circleId+"&name="+encodeURI(list.circleName)+"&img="+list.coverImgSrc;
            // }
            location.href=path;
        },
        getTimeDiff:function(time){
            var diff = '';
            var time_diff = new Date().getTime() - time; //时间差的毫秒数
            //计算出相差天数
            var days = Math.floor(time_diff/(24*3600*1000));
            if (days > 0) {
                diff += days + '天';
            }
            //计算出小时数
            var leave1 = time_diff % (24*3600*1000);
            var hours = Math.floor(leave1/(3600*1000));
            if (hours>0) {
                diff += hours + '小时';
            } else {
                if (diff !== '') {
                    diff += hours + '小时';
                }
            }
            //计算相差分钟数
            var leave2 =leave1 % (3600 * 1000);
            var minutes = Math.floor(leave2 / (60 * 1000));
            if (minutes > 0) {
                diff += minutes + '分';
            } else {
                if (diff !== '') {
                    diff += minutes + '分';
                }
            }
            //计算相差秒数
            // var leave3 = leave2%(60*1000);
            // var seconds = Math.round(leave3/1000);
            // if (seconds > 0) {
            //     diff += seconds + '秒';
            // } else {
            //     if (diff !== '') {
            //         diff += seconds + '秒';
            //     }
            // }
            return diff;
        },
        //隐藏
        getHide:function(){
            var that=this;
            console.log("1111111111111111111111111111111111111")
            console.log(that.searchObject.type)
            that.isShow=false;
            if(that.searchObject.type==2){
                console.log("2222222222222222222222222222222222")
                location.href="/friend/circleBar?type="+that.searchObject.type+"&circleId="+that.circleId+"&uid="+that.searchObject.uid+"&num="+that.num;
            }else if(that.searchObject.type==1){
                // location.href="/userHomepage?id="+that.circleId;
            }
            /*else{
                var path="/userHomepage?id="+this.circleId;
                console.log("00000000000000000")
            }*/
            this.getList(1);
        },
        //显示
        getIsshow:function(list,type){
            var that=this;
            that.isShow=true;
            that.indexs=1;
            that.type="";
            that.circleId="";
            that.name="";
            // that.img="";
            that.conversationType="";
            if(type==1){
                console.log("999999999999999999")
                console.log(JSON.stringify(list))
                if(list&&list.uid){
                    that.circleId=list.uid;
                    that.name=list.name;
                    that.img=list.headImg;
                    that.conversationType=1;
                }else{
                    if(that.friendList.length>0){
                        that.friendList&&that.friendList.forEach(function(key){
                            key.list.forEach(function(val){
                                if(val.uid==list){
                                    that.circleId=val.uid;
                                    that.name=val.name;
                                    that.img=val.headImg;
                                    that.conversationType=1;
                                }
                            });
                        });
                        if(!that.circleId&&!that.name&&!that.img&&!that.conversationType){
                            console.log("没有好友列表")
                            // console.log(that.getUserInfo(list))
                            // that.circleId=that.getUserInfo(list).uid;
                            // console.log(that.circleId)
                            that.getUserInfo(list);
                        }
                    }else{
                        that.getUserInfo(list);
                    }
                }
            }else if(type==2){
                console.log("88888888888888888866")
                console.log(JSON.stringify(list))
                that.circleList.forEach(function(key){
                    key.list.forEach(function(val){
                        //console.log(list.targetId||list)
                        console.log("22222222222"+val.circleId)
                        //console.log(val.circleId==list.targetId||list)
                        if(list.targetId){
                            if(val.circleId==list.targetId){
                                console.log("00000000000000")
                                that.circleId=val.circleId;
                                that.name=val.circleName;
                                that.img=val.coverImgSrc;
                                that.conversationType=3;
                                console.log(that.circleId+"--"+that.name+"--"+that.img)
                            }
                        }else{
                            if(val.circleId==list){
                                //console.log("00000000000000")
                                that.circleId=val.circleId;
                                that.name=val.circleName;
                                that.img=val.coverImgSrc;
                                that.conversationType=3;
                                console.log(that.circleId+"--"+that.name+"--"+that.img)
                            }
                        }
                    });
                });
                // console.log(that.circleId+"--"+that.name+"--"+that.img)
            }else if(type==3){
                console.log(list)
                if(list.senderUserId==that.userInfo.chatId){
                    if(list.content.extra){
                        that.circleId=list.targetId;
                        that.name=list.content.extra.name;
                    }else{
                        that.circleId=that.getHead(2,list.targetId).uid;
                        that.name=that.getHead(2,list.targetId).name;
                    }
                }else{
                    that.circleId=list.senderUserId;
                    that.name=list.content.user.name;
                }
                // that.img=list.content.user.portrait;
                that.conversationType=list.conversationType;
            }
            list.check=false;
            this.messageRecord();
            console.log(that.conversationType+"ddddddddd"+type);
            console.log( this.circleId+"====="+this.name+"========="+this.img)
        },
        //发送消息
        getSendMessage:function(){
            if(this.text){
                sendMessage();
                //sendRegisterMessage();
                this.text="";
            }else{
                vm.$refs.prompt.toast("发送消息不能为空！");
            }
        },
        //历史记录
        getList:function(num){
            console.log("走进历史记录")
            var newList=JSON.parse(localStorage.getItem("newList"));
            if(newList!=null){
                newList.sort(function(a,b){
                    return a.sentTime > b.sentTime;
                });
                //console.log(newList);
                var allArr = [];
                for(var i=newList.length-1;i>=0;i--){
                    var flag = true;
                    for(var j=0;j<allArr.length;j++){
                        if(newList[i].targetId == allArr[j].targetId&&newList[i].conversationType == allArr[j].conversationType){
                            flag = false;
                        }
                    }
                    if(flag){
                        allArr.push(newList[i]);
                    }
                }
                //console.log(allArr);
                if(num==1){
                    allArr.forEach(function(val){
                        val.check=false;
                    });
                }
                this.newsList=allArr;
                this.messageRecord();
            }
            console.log(this.newsList)
            // this.getIsshow()
        },
        //获取消息记录
        messageRecord:function(){
            this.messageRecordList=[];
            //根据类型和圈子id获取聊天记录
            var key=this.conversationType+"-"+this.circleId;
            var messageRecord=JSON.parse(localStorage.getItem(key));
            console.log("1111111111"+key)
            //根据类型和用户id获取聊天记录
            var uid=userInfo.chatId;
            var key1=this.conversationType+"-"+uid;
            var messageRecord1=JSON.parse(localStorage.getItem(key1));
            console.log("22222222222222"+key1)
            var messageAll=[];
            if(messageRecord&&messageRecord1){
                messageRecord1.forEach(function(val){
                    if(val.targetId==vm.circleId){
                        messageAll.push(val);
                    }
                });
                this.messageRecordList=messageRecord.concat(messageAll);
            }else if(messageRecord&&messageRecord1==null){
                this.messageRecordList=messageRecord.concat(messageAll);
            }else if(messageRecord==null&&messageRecord1){
                messageRecord1.forEach(function(val){
                    if(val.targetId==vm.circleId){
                        messageAll.push(val);
                    }
                });
                this.messageRecordList=messageAll;
            }
            this.messageRecordList.sort(function(a,b){
                return a.sentTime > b.sentTime;
            });
            console.log(this.messageRecordList)
        },
        //获取圈子头像名称
        getHead:function(type,id){
            var that=this,vals;
            if(type==1&&that.circleList){
                that.circleList.forEach(function(key){
                    key.list.forEach(function(val){
                        if(val.circleId==id){
                            vals=val;
                        }
                    });
                });
            }else if(type==2&&that.friendList){
                console.log(id)
                if(that.friendList.length>0) {
                    console.log("1111")
                    that.friendList.forEach(function (key) {
                        key.list.forEach(function (val) {
                            if (val.uid == id) {
                                vals = val;
                            }
                        });
                    });
                    if (!vals) {
                        that.getUserInfo(id,1);
                        return false;
                    }
                }else{
                    that.getUserInfo(id,1);
                    return false;
                }
            }
            return vals;
        },
        //用户信息
        getUserInfo:function(id,type){
            var that = this,ar;
            var data = {
                loginUid:userInfo.id||that.uid,
                id:id
            };
            this.ajax({url:"/user/getUserInfo", data: data, dataType: "json", method: "post"}, function (b) {
                if (b.json.code == 0 && b.json.data) {
                    if(type){
                        that.newsList.forEach(function(val){
                            if(val.targetId==id){
                                val.content.extra=b.json.data;
                            }
                        });

                    }else{
                        console.log("6666")
                        that.getUser=b.json.data;
                        that.circleId=that.getUser.uid;
                        that.name=that.getUser.name;
                        that.img=that.getUser.headImg;
                        that.conversationType=1;
                    }
                    console.log(that.getUser)
                } else {
                    vm.$refs.prompt.toast("获取信息失败！")
                }
            });

        },
        getCircleInfo:function(id){
            // console.log(this.conversationType)
            if(this.conversationType==1){
                location.href="/friend/chatSettings?id="+this.circleId;
            }else if(this.conversationType==3){
                location.href="/friend/circleInfo?circleId="+this.circleId+"&uid="+userInfo.id;
            }
        },
        getSearch:function(type,item){
            if(type==1) {
                location.href = "/friend/searchPage?indexs="+ this.indexs;
            }else if(type==2){
                console.log(item)
                if(item.content.type==1){  //乐购商品
                    location.href="/purchase/goodsDetails?type=1&productId="+item.content.modelId;
                }else if(item.content.type==2){  //自媒体视频
                    location.href="/see/selfMediaVd?id="+item.content.modelId+"&sourceType="+item.content.extra+"&uid="+userInfo.id||this.uid;
                }else if(item.content.type==3){  //企业广告视频
                    location.href="/see/adDetails?id="+item.content.modelId;
                }else if(item.content.type==4){  //城市广告视频
                    location.href="/cityAd/cityAdVideo?cityAdvId="+item.content.modelId;
                }else if(item.content.type==5){  //城市游记
                    location.href="/cityAd/travelsInfo?cityAdvId="+item.content.modelId;
                }else if(item.content.type==6){  //帖子
                    location.href="/friend/postDetails?postId="+item.content.modelId+"&uid="+userInfo.id||this.uid;
                }else if(item.content.type==8){   //爆款
                    location.href="/purchase/burstingInfo1?type=3&orderNumber="+item.content.orderNumber;   //465464&loginUid=44546
                }else if(item.content.type==7){   //拼团
                    if(item.senderUserId==userInfo.chatId){
                        location.href="/purchase/collageInfo?collageOrderId="+item.content.orderNumber;
                    }else{
                        location.href="/purchase/collageAdd?orderNumber="+item.content.orderNumber
                    }
                }else if(item.content.type==9){   //个人名片
                    location.href="/friend/chatSettings?id="+item.content.modelId;
                }
            }else if(type==3){
                console.log(item)
                location.href="/see/selfMediaVd?id="+item.mediaId+"&sourceType=1&uid="+userInfo.id||this.uid;
            }
        },
        getAdd:function(id){
            if(id){
                location.href="/userHomepage?id="+id;
            }else{
                location.href="/friend/addFriend?loginUid="+userInfo.id;
            }

        },
        getIsScreen:function(num,item){
            this.isScreen=num;
            this.pageNumber=1;
            this.mediaId=item.mediaId;
            this.number=item.type;
            this.getInfoMediaAdvCommentList();
        },
        //删除帖子
        deletePost:function(){
            var that=this;
            if(that.groupInfo.isMain==1){
                data.delType=2
            }else{
                that.getIsClassify();
                vm.$refs.prompt.toast("无权删除帖子！");
                return false;
            }
            var data={
                loginUid:that.uid,
                postId:that.postId
            };
            console.log(data);
            this.ajax({url:"/friend/deletePost",data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0){
                    that.getGroupInfo();
                }else{
                    vm.$refs.prompt.toast("删除帖子失败！");
                }
            });
        },
        //发表评论
        comment:function(){
            var that=this,data,url;
            if(!that.commentText){
                vm.$refs.prompt.toast("请输入评论内容！");
                return false;
            }
            data={
                loginUid:userInfo.id||that.uid,
                content:that.commentText
            };
            if(that.number==1){   //type 1自媒体 2集市 3圈子
                data.id=that.mediaId;
                url="/selfMedia/comment";
            }else if(that.number==2){

            }else if(that.number==3){
                data.postId=that.mediaId;
                url="/friend/postComment";
            }
            console.log(data);
            this.ajax({url:url,data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0){
                    that.commentText="";
                    that.getInfoMediaAdvCommentList();
                    that.getFriendDynamic();
                }else{
                    vm.$refs.prompt.toast("评论失败！");
                }
            });
        },
        //获取评论列表
        getInfoMediaAdvCommentList:function(){
            var that=this,url,data;
            data={
                loginUid:userInfo.id||that.uid,
                pageNumber:that.pageNumber
            };
            //postId:that.postId,
            if(that.number==1){   //type 1自媒体 2集市 3圈子
                data.id=that.mediaId;
                url="/selfMedia/getInfoMediaAdvCommentList";
            }else if(that.number==2){

            }else if(that.number==3){
                data.postId=that.mediaId;
                url="/friend/getInfoPostCommentList";
            }
            //console.log(data)
            this.ajax({url:url,data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==00&&b.json.data){
                    that.commentList=b.json.data;
                    that.commentList1=that.commentList.list;
                    if(that.commentList.pageNumber>1){
                        if(that.commentList.list.length>0) {
                            that.commentList2 = that.commentList2.concat(b.json.data.list);
                        }
                    }else{
                        that.commentList2= that.commentList1;
                    }
                    vm.loadFlag=false;
                    console.log(that.commentList)
                }else{
                    that.commentList={};
                    that.commentList1=[];
                    that.commentList2=[];
                    vm.$refs.prompt.toast("获取评论列表！");
                }
            });
        },
        //评论点赞
        praiseMediaAdvComment:function(state,commentId){
            var that=this,data,url;
            console.log(state+"----"+commentId)
            data={
                loginUid:userInfo.id||that.uid,
                commentId:commentId
            };
            if(state==0){
                data.state=1;
            }else{
                data.state=0;
            }
            if(that.number==1){   //type 1自媒体 2集市 3圈子
                url="/selfMedia/praiseMediaAdvComment";
            }else if(that.number==2){

            }else if(that.number==3){
                url="/friend/praisePostComment";
            }
            console.log(data)
            this.ajax({url:url,data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0&&b.json.data){
                    that.commentList2.forEach(function(val){
                        if(val.commentId==commentId){
                            val.praiseState=data.state;
                            val.praiseCount=b.json.data.praiseCount;
                        }
                    });
                    console.log(b.json.data)
                }else{
                    vm.$refs.prompt.toast("点赞失败！");
                }
            });
        },
        //点赞
        getPraise:function(item){
            var that=this,data,url;
            data={
                loginUid:userInfo.id||that.uid
            };
            if(item.isPraise==0){
                data.state=1;
            }else{
                data.state=0;
            }
            if(item.type==1){   //type 1自媒体 2集市 3圈子
                data.id=item.mediaId;
                url="/selfMedia/getPraise";
            }else if(item.type==2){

            }else if(item.type==3){
                data.postId=item.mediaId;
                url="/friend/praisePost";
            }
            console.log(data);
            this.ajax({url:url,data:data,dataType:"json",method:"post"},function(b){
                if(b.json.code==0){
                    that.getFriendDynamic();
                }else{
                    vm.$refs.prompt.toast("点赞失败！")
                }
            });
        },
        getCommentInfo:function(commentId){
            var path="/see/commentInfo?id="+this.mediaId+"&commentId="+commentId+"&loginUid="+userInfo.id||this.uid;
            if(this.number==3){
                path+="&type=2";
            }
            console.log(path)
            location.href=path;
        }
    }
    ,watch:{
        circleList:function(){
            var that=this;
            if(that.type==2||that.type==1){
                that.getIsshow(that.circleId,that.type);
            }
            // else if(that.type==1){
            //     this.getIsshow(this.circleId,this.searchObject.type);
            // }

        },
        news:function(){
            //1 key 1-1    数组 缓存取
            //2 key 1-1    数组[0] key不存在
            //3 key 1-1    数组 push    key 存在
            //4放回缓存中
            var key=vm.news.conversationType+"-"+vm.news.targetId;
            var messages=JSON.parse(localStorage.getItem(key));
            var newList=JSON.parse(localStorage.getItem("newList"));
            var newArr=[];
            var newArrlist=[];
            // debugger;
            if(messages!=null){newArr=messages;}
            if(newList!=null){
                newArrlist=newList;
            }
            // vm.news.check=false;
            newArr.push(vm.news);
            newArrlist.push(vm.news);
            localStorage.setItem(key,JSON.stringify(newArr));
            localStorage.setItem("newList",JSON.stringify(newArrlist));
            //console.log(vm.newsList)
            if(this.isShow){
                this.getList(1);
            }else{
                this.getList();
            }
            this.$nextTick(function(){
                // sideDeleting(".friendIndex-news .news-list a");
                sideDeleting();
            });
        },
        messageRecordList:function(){
            this.$nextTick(function(){
                var a=document.getElementById("chatPageCent");
                if(this.messageRecordList.length>0&&a!=null){
                    a.scrollTop=a.scrollHeight;
                }
            });
        }
    }
});
startInit();
function sideDeleting(name){
    console.log('dddddddd')
    console.log(name);
    //侧滑显示删除按钮
    var expansion = null; //是否存在展开的list
    // var container = document.querySelectorAll(".friendIndex-news .news-list a");
    var container = document.getElementsByClassName(".news-list");
    for(var i = 0; i < container.length; i++){
        var x, y, X, Y, swipeX, swipeY;
        container[i].addEventListener('touchstart', function(event) {
            x = event.changedTouches[0].pageX;
            y = event.changedTouches[0].pageY;
            swipeX = true;
            swipeY = true ;
            if(expansion){   //判断是否展开，如果展开则收起
                expansion.className = "clearfix";
            }
        });
        container[i].addEventListener('touchmove', function(event){
            X = event.changedTouches[0].pageX;
            Y = event.changedTouches[0].pageY;
            // 左右滑动
            if(swipeX && Math.abs(X - x) - Math.abs(Y - y) > 0){
                // 阻止事件冒泡
                event.stopPropagation();
                if(X - x > 10){   //右滑
                    event.preventDefault();
                    this.className = "";    //右滑收起
                    //console.log("右滑")
                }
                if(x - X > 10){   //左滑
                    event.preventDefault();
                    this.className = "clearfix swipeleft";   //左滑展开
                    //console.log("左滑")
                    expansion = this;
                }
                swipeY = false;
            }
            // 上下滑动
            if(swipeY && Math.abs(X - x) - Math.abs(Y - y) < 0) {
                // 阻止事件冒泡
                event.stopPropagation();
                if(Y - y > 10){   //上滑
                    event.preventDefault();
                    // this.className = "";    //右滑收起
                    console.log("上滑")
                }
                if(y - Y > 10){   //下滑
                    event.preventDefault();
                    // this.className = "clearfix swipeleft";   //左滑展开
                    console.log("下滑")
                    expansion = this;
                }
                swipeX = false;
            }
        });
    }
}
var instance = null;
function startInit(user,targetId){
    var params = {
        appKey : getValue("appKey"),
        token : getValue("token")||userInfo.token
        // navi : getValue("navi")
    };
    console.log(params)
    var userId = "";
    var callbacks = {
        getInstance : function(instance){
            // 直接初始化
            RongIMLib.RongIMEmoji.init();
            // 通过配置初始化
            var config = {
                size: 24, // 大小, 默认 24, 建议15 - 55
                url: '//f2e.cn.ronghub.com/sdk/emoji-48.png', // 所有 emoji 的背景图片
                lang: 'zh' // 选择的语言, 默认 zh
            };
            RongIMLib.RongIMEmoji.init(config);
        },
        getCurrentUser : function(userInfo){
            console.log(userInfo.userId);
            userId = userInfo.userId;
            console.log("链接成功；userid=" + userInfo.userId);
            document.titie = ("链接成功；userid=" + userInfo.userId);
            //加入聊天室
            //joinChatRoom();
            //发送消息
            //sendMessage();
            //获取单群聊历史消息
            //singleChatInfo()
            //获取会话列表
            //getInstance();
            checkUnreadMessage();
        }
    };

    initrongyun(params,callbacks);
}
function getValue(id){
    return document.getElementById(id).value;
}
//获取单群聊历史消息
function getInstance(){
    RongIMClient.getInstance().getConversationList({
        onSuccess: function(list) {
            // list => 会话列表集合。
            //console.log(list)
            console.log(JSON.stringify(list))
            console.log("22222222222222222")
            vm.news=list;
        },
        onError: function(error) {
            // do something...
        }
    },null);
}
function initrongyun(params, callbacks, modules){
    var appKey = params.appKey;
    var token = params.token;
    var navi = params.navi || "";
    modules = modules || {};
    var RongIMLib = modules.RongIMLib || window.RongIMLib;
    var RongIMClient = RongIMLib.RongIMClient;
    var protobuf = modules.protobuf || null;
    var config = {};
    //私有云切换navi导航，私有云格式 '120.92.10.214:8888'
    if(navi !== ""){
        config.navi = navi;
    }
    //私有云切换api,私有云格式 '172.20.210.38:81:8888'
    var api = params.api || "";
    if(api !== ""){
        config.api = api;
    }
    //support protobuf url + function
    if(protobuf != null){
        config.protobuf = protobuf;
    }
    var dataProvider = null;
    var imClient = params.imClient;
    if (imClient) {
        dataProvider = new RongIMLib.VCDataProvider(imClient);
    }
    RongIMLib.RongIMClient.init(appKey, dataProvider, config);
    var propertys = ["type","imgSrc","title","source","sex","level","extra","user","modelId","orderNumber"]; // 消息类中的属性名。
    registerMessage("ShareMessage",propertys);
    var propertys1 = ["type","imgSrc","title","discount","pintegral","orderNumber","modelId","extra","user","source"]; // 消息类中的属性名。
    registerMessage1("ShopMessage",propertys1);
    var instance = RongIMClient.getInstance();
    // 连接状态监听器
    RongIMClient.setConnectionStatusListener({
        onChanged: function (status) {
            // console.log(status);
            switch (status) {
                case RongIMLib.ConnectionStatus["CONNECTED"]:
                case 0:
                    console.log("连接成功");
                    callbacks.getInstance && callbacks.getInstance(instance);
                    break;

                case RongIMLib.ConnectionStatus["CONNECTING"]:
                case 1:
                    console.log("连接中");
                    break;

                case RongIMLib.ConnectionStatus["DISCONNECTED"]:
                case 2:
                    console.log("当前用户主动断开链接");
                    break;

                case RongIMLib.ConnectionStatus["NETWORK_UNAVAILABLE"]:
                case 3:
                    console.log("网络不可用");
                    break;

                case RongIMLib.ConnectionStatus["CONNECTION_CLOSED"]:
                case 4:
                    console.log("未知原因，连接关闭");
                    break;

                case RongIMLib.ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"]:
                case 6:
                    console.log("用户账户在其他设备登录，本机会被踢掉线");
                    break;

                case RongIMLib.ConnectionStatus["DOMAIN_INCORRECT"]:
                case 12:
                    console.log("当前运行域名错误，请检查安全域名配置");
                    break;
            }
        }
    });
    /*
    文档：http://www.rongcloud.cn/docs/web.html#3、设置消息监听器
    注意事项：
        1：为了看到接收效果，需要另外一个用户向本用户发消息
        2：判断会话唯一性 ：conversationType + targetId
        3：显示消息在页面前，需要判断是否属于当前会话，避免消息错乱。
        4：消息体属性说明可参考：http://rongcloud.cn/docs/api/js/index.html
    */
    RongIMClient.setOnReceiveMessageListener({
        // 接收到的消息
        onReceived: function (message) {
            // 判断消息类型
            console.log("新消息: " + message.targetId);
            console.log(JSON.stringify(message));
            //console.log("1111111111111111111111")
            message.check=true;
            vm.news=message;
            console.log(vm.news)
            //callbacks.receiveNewMessage && callbacks.receiveNewMessage(message);
        }
    });
    //开始链接
    RongIMClient.connect(token, {
        onSuccess: function(userId) {
            callbacks.getCurrentUser && callbacks.getCurrentUser({userId:userId});
            console.log("链接成功，用户id：" + userId);
            // var propertys = ["type","imgSrc","title","source","sex","level","extra","user"]; // 消息类中的属性名。
            // registerMessage("ShareMessage",propertys);
            // var propertys1 = ["type","imgSrc","title","discount","pintegral","orderNumber","extra","user"]; // 消息类中的属性名。
            // registerMessage("ShopMessage",propertys1);
        },
        onTokenIncorrect: function() {
            console.log('token无效');
        },
        onError:function(errorCode){
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = '未知错误';
                    break;
                case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
            }
            console.log(errorCode);
        }
    }, '');
    var callback = {
        onSuccess: function(userId) {
            console.log("Reconnect successfully." + userId);
        },
        onTokenIncorrect: function() {
            console.log('token无效');
        },
        onError:function(errorCode){
            console.log(errorcode);
        }
    };
    var configs = {
        // 默认 false, true 启用自动重连，启用则为必选参数
        auto: true,
        // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
        url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
        // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
        rate: [100, 1000, 3000, 6000, 10000]
    };
    RongIMClient.reconnect(callback, configs);
}
//发送文本消息
function sendMessage(){
    var msg = new RongIMLib.TextMessage(
        {
            content:vm.text,
            extra:"",
            user : {
                "id" : vm.userInfo.id,	//不支持中文及特殊字符
                "name" : vm.userInfo.name,
                "portrait" :vm.userInfo.headImg //vm.img
                // "text":""
            }
        }
    );
    var conversationtype;
    if(vm.conversationType==1){
        conversationtype= RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可
    }else if(vm.conversationType==3){
        conversationtype = RongIMLib.ConversationType.GROUP; // 群聊,其他会话选择相应的消息类型即可
    }
    console.log(conversationtype)
    var targetId =vm.circleId; // 目标 Id "c6ba28631e514159b1ccade146ea2c06";//
    console.log("targetId="+targetId);
    RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
            onSuccess: function (message) {
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                console.log(message)
                var key=message.conversationType+"-"+message.senderUserId;
                var messages=JSON.parse(localStorage.getItem(key));
                var newList=JSON.parse(localStorage.getItem("newList"));
                var newArr=[];
                var newArrlist=[];
                // debugger;
                if(messages!=null){
                    newArr=messages;
                }
                if(newList!=null){
                    newArrlist=newList;
                }
                newArr.push(message);
                newArrlist.push(message);
                localStorage.setItem(key,JSON.stringify(newArr));
                localStorage.setItem("newList",JSON.stringify(newArrlist));
                vm.messageRecord();
                // var mess={
                //     targetId:vm.circleId,
                //     senderUserId:vm.userInfo.id,
                //     content:vm.text
                // };
                // this.messageRecordList.push(JSON.stringify(mess));
                // newArr=JSON.parse(localStorage.getItem(key));
                //console.log(JSON.stringify(newArr));
            },
            onError: function (errorCode,message) {
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    default :
                        info = x;
                        break;
                }
                console.log('发送失败:' + info);
            }
        }
    );
}
function checkUnreadMessage(){
    /*
    http://www.rongcloud.cn/docs/web.html#5_5、检测是否有未读的消息
    此接口必须在init()方法之后调用，但不依赖于connect
    只返回true/false，不返回具体的未读数量
    若连接成功后调用此方法将一直返回 false。
    */
    var start = new Date().getTime();
    console.log(token)
    var token=getValue("token")||userInfo.token;
    RongIMClient.getInstance().hasRemoteUnreadMessages(token,{
        onSuccess:function(hasMessage){
            if(hasMessage){
                console.log("有未读的消息")
                // 有未读的消息
            }else{
                console.log("没有未读的消息")
                // 没有未读的消息
            }

            //showResult("检查未读消息成功",hasMessage,start);

        },onError:function(err){
            //showResult("检查未读消息失败",err,start);
        }
    });
}
//定义
function registerMessage(type,propertys){
    var messageName = type; // 消息名称。
    var objectName = "hkzh:share"; // 消息内置名称，请按照此格式命名 *:* 。
    /*if(vm.number==1){
        var objectName = "hkzh:share"; // 消息内置名称，请按照此格式命名 *:* 。
    }else if(vm.number==2){
        var objectName = "hkzh:share"; // 消息内置名称，请按照此格式命名 *:* 。
    }*/
    var mesasgeTag = new RongIMLib.MessageTag(true,true); //true true 保存且计数，false false 不保存不计数。

    RongIMClient.registerMessageType(messageName,objectName,mesasgeTag,propertys);
}
//定义
function registerMessage1(type,propertys){
    var messageName = type; // 消息名称。hkzh:share
    var objectName = "hkzh:burstingshare"; // 消息内置名称，请按照此格式命名 *:* 。
    var mesasgeTag = new RongIMLib.MessageTag(true,true); //true true 保存且计数，false false 不保存不计数。
    RongIMClient.registerMessageType(messageName,objectName,mesasgeTag,propertys);
}
//文档高度
function getDocumentTop() {
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;    return scrollTop;
}
//可视窗口高度
function getWindowHeight() {
    var windowHeight = 0;    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}
//滚动条滚动高度
function getScrollHeight() {
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;

}
window.onscroll=function(){
    if(vm.indexs!=4){
        return false;
    }
    var loadFlag = vm.friendDynamic.lastPage;
    //监听事件内容
    if(getScrollHeight()==getWindowHeight() + getDocumentTop()){
        //当滚动条到底时,这里是触发内容
        if(!loadFlag){
            vm.loadFlag=true;
            vm.pageNumber++;
            vm.getFriendDynamic();
            lazyload();
        }else{
            vm.$refs.prompt.toast("没有更多了！")
        }
    }
};
function lazyload(){
    $("img.lazy").lazyload();
}